<?php
/**
 * Joomla! 1.5 component jhtraq
 *
 * @version $Id: view.html.php 2010-03-09 08:28:06 svn $
 * @author JHShop
 * @package Joomla
 * @subpackage jhtraq
 * @license GNU/GPL
 *
 * Traq type system for Joomla
 *
 * This component file was created using the Joomla Component Creator by Not Web Design
 * http://www.notwebdesign.com/joomla_component_creator/
 *
 */

// no direct access
defined('_JEXEC') or die('Restricted access');

jimport( 'joomla.application.component.view');

/**
 * HTML View class for the jhtraq component
 */
class JhtraqViewTickets extends JView {
	function display($tpl = null) {
            $project = JRequest::getVar('project');
	    $session = JSession::getInstance($project,array());

		if ($_POST) {
                    $session->set('post', $_POST);
		}
		$_POST = $session->get('post');
            if(!isset($_GET['limitstart']))
                JRequest::setVar('limitstart',0);
		
		$model =& JhtraqHelper::getModel('jhtraq');
		$project = JRequest::getVar('project');
		$this->project = $model->getProjectBySlug($project);
		if(JRequest::getVar('task') != '')
		{
			$t = JRequest::getVar('task');
			$this->$t();
		}
		
		if(JRequest::getVar('layout') == 'view')
		{
			$this->ticket = $model->ticketGet(array('ticket_id'=>JRequest::getVar('ticket'),'project_id'=>$this->project->id));
		}else{
			$where = $this->buildWhere();
			$this->tickets = $model->getTicketTickets($this->project->id,$where);
			$this->pagination = $model->getPagination();
		}
		
		$user = JFactory::getUser();
		$this->captchaHTML = "";
		if (!$user->id) {
			$model =& JhtraqHelper::getModel('settings');
	   	    $settings =$model->getConfig();
            require_once(JPATH_BASE . '/components/com_jhtraq/extras/captcha/' . $settings['captcha_engine']);
            $this->captchaHTML = genCaptchaHTML();
		}
        parent::display($tpl);
    }
	
	/**
	 * Tasks
	 */
	
	function delete()
	{
		$user =& JFactory::getUser();
		if(in_array((int)$user->id, explode(",", $this->project->managers)))
		{
			$model =& JhtraqHelper::getModel('jhtraq');
			$model->deleteTicket(JRequest::getVar('ticket'));
		}else{
			die('NOT AUTH');
		}
		return;
	}
	
	function update()
	{
		$user =& JFactory::getUser();
		if(in_array((int)$user->id, explode(",", $this->project->managers)))
		{
			$model =& JhtraqHelper::getModel('jhtraq');
			$this->ticket = $model->ticketGet(array('id'=>JRequest::getVar('ticket')));
			//print_r($this->ticket);
			
			$model->updateTicket($this->ticket,$this->project);
		}
	}
	
	function ticket_columns()
	{
		$columns = array(
		'ticket',
						 'summary',
						 'status',
						 'owner',
						 'type',
						 'severity',
						 'component',
						 'milestone',
						 'version',
						 'assigned_to'
						 );
						// ($hook = FishHook::hook('function_ticket_columns')) ? eval($hook) : false;
						 return $columns;
	}
	
	function buildWhere()
	{
	//	if(!isset($_POST['filter']) && !isset($_POST['completed']))
	//		return '';
// 	print_r($_SESSION);
		$where = array();
		$scompleted = isset($_SESSION['hidecompleted'])?$_SESSION['hidecompleted']:0;
		$completed = true;
		if(isset($_POST['filter']))
		{
			foreach($_POST['filter'] as $filter=>$value)
			{
				if($value != '')
				{
					$where[] = "$filter = '$value'";
// 					if($filter == 'status')
// 					{
// 						$completed = false;
// 					}
				}
			}
		}elseif(isset($_GET['filter']))
		{
			foreach($_GET['filter'] as $filter=>$value)
			{
				if($value != '')
				{
					$where[] = "$filter = '$value'";
// 					if($filter == 'status')
// 					$completed = false;
				}
			}
		}
		
		if(isset($_REQUEST['completed']))
		{
			if($scompleted > 0)
			{
				$completed = true;
				$_SESSION['hidecompleted'] = 0;
			}else{
				$completed = false;
				$_SESSION['hidecompleted'] = 1;
			}
		}else{
			if($scompleted > 0)
			{
				$completed = false;
			}else{
				$completed = true;
			}
		}
		$this->completed = $completed;
		if(!$completed)
		{
			$where[] = 'closed = 0';
		}
		
	
		
		$string = '';
		if(count($where))
			$string = "AND " . implode(" AND ", $where);
		return $string;
	}
	
	function buildOptions($key, $pid=0)
	{
		
		$sel = isset($_POST['filter'][$key])?$_POST['filter'][$key]:'';
		$db =& JFactory::getDBO();
		switch($key)
		{
			case 'status':
				$db->setQuery("SELECT * FROM #__jhtraq_ticket_status ORDER BY name ASC");	
				break;
			case 'type':
				$db->setQuery("SELECT * FROM #__jhtraq_ticket_types ORDER BY name ASC");
				break;
			case 'severity':
				$db->setQuery("SELECT * FROM #__jhtraq_severities ORDER BY name ASC");
				break;
			case 'priority':
				$db->setQuery("SELECT * FROM #__jhtraq_priorities ORDER BY name ASC");
				break;
			case 'milestone_id':
				
				$db->setQuery("SELECT id,milestone as name FROM #__jhtraq_milestones WHERE project_id='".(int)$pid."' order by id asc");
				break;
			case 'version_id':
				$db->setQuery("SELECT id,version as name FROM #__jhtraq_versions WHERE project_id='".(int)$pid."' order by id asc");
				break;
				
			default:
				return;
				break;
		}
		$rows = $db->loadAssocList();
		$html = '';
		
		foreach($rows as $row)
		{
			$selected = ($sel == $row['id'])?'Selected':'';
			$html .=  '<option value="'.$row['id'].'" '.$selected.'>'. $row['name'] . '</option>';
		}
		
		echo $html;
	}
	
	function ticket_type($type_id)
	{
		$db =& JFactory::getDBO();
		$db->setQuery("SELECT name FROM #__jhtraq_ticket_types WHERE id='".$type_id."' LIMIT 1");
		return $db->loadResult();
	}
	
	function ticket_priority($priority_id)
	{
		$db =& JFactory::getDBO();
		$db->setQuery("SELECT name FROM #__jhtraq_priorities WHERE id='".$priority_id."' LIMIT 1");
		return $db->loadResult();
	}
	
	function ticket_severity($severity_id)
	{
		$db =& JFactory::getDBO();
		$db->setQuery("SELECT name FROM #__jhtraq_severities WHERE id='".$severity_id."' LIMIT 1");
		return $db->loadResult();
	}
	
	function ticket_status($status_id)
	{
		if($status_id == 0)
			return JText::_('Unconfirmed');
		$db =& JFactory::getDBO();
		$db->setQuery("SELECT name FROM #__jhtraq_ticket_status WHERE id='".$status_id."' LIMIT 1");
		return $db->loadResult();
	}
	
	function buildSelectOptions($key, $pid=0)
	{
		// 		$sel = isset($_REQUEST['filter'][$key])?$_REQUEST['filter'][$key]:'';
		print_r($_POST);
		if($key == 'milestone' || $key == 'component' || $key == 'version')
		{
			$skey = "{$key}_id";
			$sel = isset($_POST[$key])?$_POST[$key]:$this->ticket[$skey];
		}else{
			$sel = isset($_POST[$key])?$_POST[$key]:$this->ticket[$key];
		}
		//echo $sel;
		$db =& JFactory::getDBO();
		switch($key)
		{
			case 'status':
				$db->setQuery("SELECT * FROM #__jhtraq_ticket_status ORDER BY name ASC");	
				break;
			case 'type':
				$db->setQuery("SELECT * FROM #__jhtraq_ticket_types ORDER BY name ASC");
				break;
			case 'severity':
				$db->setQuery("SELECT * FROM #__jhtraq_severities ORDER BY name ASC");
				break;
			case 'priority':
				$db->setQuery("SELECT * FROM #__jhtraq_priorities ORDER BY name ASC");
				break;
			case 'milestone':
				$db->setQuery("SELECT id,milestone as name FROM #__jhtraq_milestones WHERE project_id='".(int)$this->project->id."' and locked != 1 order by id asc");
				break;
			case 'version':
				$db->setQuery("SELECT id,version as name FROM #__jhtraq_versions WHERE project_id='".(int)$this->project->id."' order by id asc");
				break;
			case 'assigned_to':
				$db->setQuery("Select username as name, id from #__users where id in(" . $this->project->managers . ")");
				break;
			case 'component':
				$db->setQuery("SELECT id, name FROM #__jhtraq_components WHERE project_id='".(int)$this->project->id."' order by id asc");
				//	$db->query();
				//	print_r($db);
				break;
				
			default:
				return;
				break;
		}
		$rows = $db->loadAssocList();
		$html = '';
		
		foreach($rows as $row)
		{
			$selected = ($sel == $row['id'])?'Selected':'';
			$html .=  '<option value="'.$row['id'].'" '.$selected.'>'. $row['name'] . '</option>';
		}
		
		echo $html;
	}
	
	function attachfile()
	{
		$msg = '';
		$imgPath = JPATH_BASE . DS . 'media'. DS . 'jhtraq' . DS . $this->project->slug;
		if(!file_exists($imgPath))
		{
			if(!mkdir($imgPath,0777,true))
			{
				$msg = JText::_('Folder not writable / not found for uploads' . $imgPath);
			}
		}
		if($msg == '')
		{
				$allowed = "/[^a-z0-9.\-\_]/i";
			//	print_r($_FILES);
				//preg_replace($allowed,"",$str));
				$n = strtotime("NOW") . $_FILES['file']['name'];
				$n = preg_replace($allowed,'',$n);
				
				if(move_uploaded_file($_FILES['file']['tmp_name'], "$imgPath/$n"))
				{
					$msg = JText::_('File Uploaded');
					$db = JFactory::getDBO();
					$user = JFactory::getUser();
					
					$db->setQuery("Insert into #__jhtraq_attach(`mask`,`filename`,`ownername`,`ticket_id`,`project_id`,`create_date`)
					values
					('".preg_replace($allowed,'',$_FILES['file']['name'])."','".$n."','".$user->username."','".JRequest::getVar('ticket')."','".$this->project->id."','".time()."')");
					$db->query();
				//	print_r($db);
				//	die();
				}else{
					$msg = JText::_('File upload Failed');
				}
				
		}
		$mainframe =& JFactory::getApplication();
		$mainframe->redirect(JRoute::_('index.php?option=com_jhtraq&view=tickets&layout=view&project='.$this->project->slug.'&ticket='.JRequest::getVar('ticket')),$msg);
// 		//echo $imgPath;
// 		print_r($_POST);
// 		print_r($_FILES);
// 		print_r($this->project);
// 		die();
	}
	
	
	function download()
	{
		$att = JRequest::getVar('attachment',0);
		$db =& JFactory::getDBO();
		$db->setQuery("Select * from #__jhtraq_attach where id='$att'");
		$row = $db->loadObject();
		if(!$row->id)
			DIE('File Not Available');
		
		$file = JPATH_BASE . DS . 'media'. DS . 'jhtraq' . DS . $this->project->slug .DS. $row->filename;
		$mask = basename($row->mask);
		$mime = 'application/octet-stream';
		$encoding = 'binary';
		header('Pragma: public');
		header('Expires: 0');
		header('Content-Description: File Transfer');
		header('Content-Type: ' . $mime);
		header('Content-Transfer-Encoding: ' . $encoding);
		header('Content-Disposition: attachment; filename=' . ($mask ? $mask : basename($file)));
		header('Content-Length: ' . filesize($file));
		
		$file = readfile($file, 'rb');
		
		print($file);
		
		$mainframe =& JFactory::getApplication();
		$mainframe->close();
	}
	
	function addcomment()
	{
		$user =& JFactory::getUser();
		if(!$user->id)
		{
		    $modelsettings =& JhtraqHelper::getModel('settings');
	   	    $settings =$modelsettings->getConfig();
            require_once(JPATH_BASE . '/components/com_jhtraq/extras/captcha/' . $settings['captcha_engine']);
            if(!validateCaptcha($_POST['captcha']))
            {
                 JRequest::setVar('layout', 'view' );
                 $this->captcha_error = JText::_('COM_JHTRAQ_SECURITY_CODE');
				 return false;
			}
	
		}
		
		$user_name = (isset($user->username))?$user->username:$_POST['name'];
		$user_id = (int)$user->id;
		$ticket = JRequest::getVar('ticket');
		$db =& JFactory::getDBO();
		$db->setQuery("Select id from #__jhtraq_tickets where ticket_id='$ticket' and project_id='".$this->project->id."'");
		$ticket_id = $db->loadResult();
		//print_r($db);
		//die();
		
// 		/*die*/($ticket_id);
		$project_id = $this->project->id;
		$comment = JRequest::getVar('comment');
		$timestamp = time();
		
		$db->setQuery("Insert into #__jhtraq_ticket_history set user_id='$user_id',user_name='$user_name',timestamp='$timestamp',ticket_id='$ticket_id',project_id='$project_id',comment='".$db->getEscaped($comment)."'");
		$db->query();
		$mainframe =& JFactory::getApplication();
		$mainframe->redirect(JRoute::_('index.php?option=com_jhtraq&view=tickets&project='.$this->project->slug), JText::_('Comments Added'));
		$mainframe->close();
		
	}
	
	function delete_comment()
	{
		$cid = $_POST['comment'];
		$db =& JFactory::getDBO();
		$db->setQuery("Delete from #__jhtraq_ticket_history where id='".(int)$cid."'");
		$db->query();
		$mainframe =& JFactory::getApplication();
		$mainframe->redirect(JRoute::_('index.php?option=com_jhtraq&view=tickets&layout=view&project='.$this->project->slug.'&ticket='.JRequest::getVar('ticket')), JText::_('Comments Deleted'));
		
	}
	
}
?>